<template>
    <van-form @submit="onSubmit" class="my-form">
        <h2>用户登陆</h2>
        <van-cell-group inset>
            <van-field v-model="mobile" name="mobile" label="电话" placeholder="请输入电话号码"
                :rules="[{ required: true, message: '请填写电话号码' }]" />
            <hr />
            <van-field v-model="password" type="password" name="password" label="密码" placeholder="请输入密码"
                :rules="[{ required: true, message: '请填写密码' }]" />
        </van-cell-group>
        <div style="margin: 20px;">
            <van-button round block type="primary" native-type="submit">
                点击登陆
            </van-button>
        </div>
    </van-form>
</template>
  
<script setup lang='ts'>
import { ref, onUnmounted } from 'vue'
import $bus from '../tool/eventBus'
import { userLogin } from '../api/apis'
import { useStore } from 'vuex';
import { useRoute, useRouter } from 'vue-router';

const store = useStore()
const router = useRouter()
const route = useRoute()

if (store.state.token) {
    router.push('/center')
}


// 底部导航的切换显示隐藏
$bus.emit('tabBarContral', false)
onUnmounted(() => {
    $bus.emit('tabBarContral', true)
})

const mobile = ref('');
const password = ref('');
const onSubmit = async (values: any) => {
    console.log('submit', values);
    const res = await userLogin(values);
    console.log(res);
    // 触发 store 保存 token
    store.dispatch('updateToken', res.data._token)
    // 路由跳转
    console.log(route.query.refer);
    
    if(route.query.refer){
        router.push(route.query.refer as string)
    }else{
        router.push('/center')
    }
    
};
</script>
  
<style scoped lang='scss'>
.my-form {
    margin: 36px;
    margin-top: 100px;

    h2 {
        text-align: center;
        font-size: 21px;
        color: #666;
        margin-bottom: 21px;
    }
}
</style>